package com.atguigu.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.client.CartFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.entity.CartInfo;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.UserAddress;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单明细表 前端控制器
 * </p>
 *
 * @author fumeng
 * @since 2021-11-11
 */
@RestController
@RequestMapping("/order")
public class OrderDetailController {
    @Autowired
    CartFeignClient cartFeignClient;
    @Autowired
    UserFeignClient userFeignClient;
    @Autowired
    OrderInfoService orderInfoService;
    //1.订单确认信息
    @GetMapping("/confirm")
    public RetVal<Map<String, Object>> confirm(HttpServletRequest request){
        //a.获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //b.获取用户收货地址列表
        List<UserAddress> userAddressList = userFeignClient.queryAddressByUserId(userId);
        //c.获取送货清单
        List<CartInfo> selectedProductList = cartFeignClient.getSelectedProduct(userId);
        //d.商品总金额
        BigDecimal totalMoney = new BigDecimal(0);
        //1.商品件数
        int totalNum = 0;
        //2.商品列表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(selectedProductList)){
            for (CartInfo cartInfo : selectedProductList) {
                //把cartInfo信息转换成orderDetail
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderPrice(cartInfo.getCartPrice());
                orderDetail.setSkuNum(cartInfo.getSkuNum()+"");
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setSkuId(cartInfo.getSkuId());
                //订单总金额
                totalMoney  = totalMoney.add(cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
                //商品件数
                totalNum += cartInfo.getSkuNum();
                orderDetailList.add(orderDetail);
            }
        }


        Map<String, Object> retMap = new HashMap<>();

        //地址信息
        retMap.put("userAddressList",userAddressList);
        //送货清单信息
        retMap.put("detailArrayList",orderDetailList);
        //商品数量
        retMap.put("totalNum",orderDetailList.size());
        //商品总金额
        retMap.put("totalMoney",totalMoney);
        //生成一个流水号
        String tradeNo = orderInfoService.getTradeNo(userId);
        retMap.put("tradeNo",tradeNo);

        return RetVal.ok(retMap);
    }


    //http://api.gmall.com/order/submitOrder?tradeNo=null
    //2.保存订单信息
    @PostMapping("/submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //获取id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //判断是否是无刷新回退重复提交订单
        //拿到从页面传递过来的流水号
        String tradeNo = request.getParameter("tradeNo");
        //把页面的流水号和redis里面的进行比较
        boolean flag  = orderInfoService.checkTradeNo(tradeNo, userId);
        if (!flag) {
            return RetVal.fail().message("不能重复提交订单！");
        }
        //删除redis流水号
        orderInfoService.deleteTradeNo(userId);
        //验证库存和价格
        List<String> warningInfoList=orderInfoService.checkStockAndPrice(orderInfo,userId);
        //验证不通过
        if(warningInfoList.size()>0){
            //导入该包 org.apache.commons.lang3.StringUtils
            return RetVal.fail().message(StringUtils.join(warningInfoList,","));
        }

        Long detail = orderInfoService.saveOrderInfoAndDetail(orderInfo);
        return RetVal.ok(detail);
    }

    //3.获取订单信息
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //4.拆单接口编写 http://order.gmall.com/order/splitOrder
    @PostMapping("splitOrder")
    public String splitOrder(@RequestParam Long orderId,@RequestParam String wareHouseIdSkuIdMapJson){
        return orderInfoService.splitOrder(orderId,wareHouseIdSkuIdMapJson);
    }

    //5.给秒杀提供的提交订单数据接口
    @PostMapping("/saveSeckillOrder")
    public Long saveSeckillOrder(@RequestBody OrderInfo orderInfo){
        return orderInfoService.saveOrderInfoAndDetail(orderInfo);
    }




}